<script setup lang="ts">
import CustomNavbar from '@/pages/index/componets/CustomNavbar.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from '@/pages/index/componets/CategoryPanel.vue'
import HotPanel from '@/pages/index/componets/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/components'
import PageSkeleton from '@/pages/index/componets/PageSkeleton.vue'
import { useGuessList } from '@/composables'

const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}
const hotList = ref<HotItem[]>([])
const getHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
//引入组合式函数
const { guessRef, onScrolltolower } = useGuessList()
const isLoading = ref(false)
//页面加载时触发
onLoad(() => {
  isLoading.value = true
  getHomeBannerData()
  getHomeCategoryData()
  getHotData()
  isLoading.value = false
})
// 下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置猜你喜欢组件数据
  guessRef?.value!.resetData()
  // 加载数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHotData(),
    guessRef?.value!.getMore(),
  ])
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <!--    自定义导航栏-->
  <custom-navbar></custom-navbar>
  <scroll-view
    scroll-y
    class="scroll-view"
    @scrolltolower="onScrolltolower()"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh()"
    :refresher-triggered="isTriggered"
  >
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <!--    轮播图-->
      <XtxSwiper :list="bannerList"></XtxSwiper>
      <!--    分类-->
      <category-panel :list="categoryList"></category-panel>
      <!--    推荐-->
      <hot-panel :list="hotList"></hot-panel>
      <!--    猜你喜欢-->
      <XtxGuess ref="guessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  // 按列布局
  flex-direction: column;
}

.scroll-view {
  flex: 1;
}
</style>
